<!-- 
  参考文档：https://juejin.cn/post/7027977252331585544
 -->
<script setup lang="ts">
import { nextTick, ref, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

defineOptions({
  name: 'DbEditor'
})
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: 500
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:modelValue'])

// 编辑器ref
const editorRef = shallowRef()
// 编辑器配置
const editorConfig = ref({
  placeholder: '请输入...'
})
// 编辑器高度
const editorHeight = ref(300)
// 工具栏配置
const toolbarConfig = ref({
  excludeKeys: ['group-image', 'group-video']
})

/**
 * 创建完成回调
 */
function handleCreated(editor: any) {
  editorRef.value = editor
  nextTick(() => {
    const toolBarDom = document.getElementById('toolBarRef')
    if (toolBarDom) {
      editorHeight.value = props.height - toolBarDom.getBoundingClientRect().height
    }

    // 打印菜单keys，用于移除
    // const toolbar = DomEditor.getToolbar(editorRef.value)
    // const curToolbarConfig = toolbar?.getConfig()
  })
}
/**
 * 内容变化回调
 */
function handleChange(editor: any) {
  emits('update:modelValue', editor.getHtml())
}
</script>

<template>
  <div class="db-editor-bg" :style="`height:${height}px;`">
    <template v-if="disabled">
      <div class="db-editor-disabled" v-html="modelValue"></div>
    </template>
    <template v-else>
      <Toolbar id="toolBarRef" :default-config="toolbarConfig" :editor="editorRef" mode="default" />
      <Editor
        :default-config="editorConfig"
        mode="default"
        v-bind:modelValue="modelValue"
        :style="`height:${editorHeight}px;`"
        @on-change="handleChange"
        @on-created="handleCreated"
      />
    </template>
  </div>
</template>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.db-editor-bg {
  width: 100%;
  border: 1px solid lightgray;
  overflow: hidden;
  margin-bottom: 20px;
  .db-editor-disabled {
    width: 100%;
    padding: 0 10px;
    box-sizing: border-box;
  }
}
</style>
